package applications.callcost.listeners;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import applications.callcost.R;

public class ArrowTouchListener implements View.OnTouchListener{
	
	EditText text;
	Handler handler = new Handler();
	boolean inc;
	
	public ArrowTouchListener(EditText ed){
		text=ed;
	}
	
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
		       if(inc){
		    	   try{
						int x=Integer.parseInt(text.getText().toString());
						text.setText(""+(x+1));
						handler.postDelayed(mUpdateTimeTask, 125);
					}catch(NumberFormatException e){
					}
		       }else{
		    	   try{
						int x=Integer.parseInt(text.getText().toString());
						if(x<=0)
							return;
						text.setText(""+(x-1));
						handler.postDelayed(mUpdateTimeTask, 125);
					}catch(NumberFormatException e){
					}
		       }
		   }
		};


	public boolean onTouch(View v, MotionEvent event) {
		
		if(v.getId()==R.id.decrement){
			switch(event.getAction()){
			case MotionEvent.ACTION_DOWN:
				inc=false;
				try{
					int x=Integer.parseInt(text.getText().toString());
					if(x<=0)
						return true;
					text.setText(""+(x-1));
				}catch(NumberFormatException e){
					return true;
				}
				handler.removeCallbacks(mUpdateTimeTask);
				handler.postDelayed(mUpdateTimeTask, 500);
				break;
				
			case MotionEvent.ACTION_UP:
				handler.removeCallbacks(mUpdateTimeTask);
				break;
			}
			
		}
		else if(v.getId()==R.id.increment){
			switch(event.getAction()){
			case MotionEvent.ACTION_DOWN:
				inc=true;
				try{
					int x=Integer.parseInt(text.getText().toString());
					text.setText(""+(x+1));
				}catch(NumberFormatException e){
					return true;
				}
				handler.removeCallbacks(mUpdateTimeTask);
				handler.postDelayed(mUpdateTimeTask, 500);
				break;
				
			case MotionEvent.ACTION_UP:
				handler.removeCallbacks(mUpdateTimeTask);
				break;
			}
		}
		
		return true;
	}

}
